package com.king.base.auth.service;

import com.king.base.auth.security.JwtUser;
import com.king.base.exception.EntityNotFoundException;
import com.king.base.domain.user.User;
import com.king.base.service.user.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author TianYZ
 * @date 2019-06-15
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String loginName){

        User user = userService.findByName(loginName);
        if (user == null) {
            throw new EntityNotFoundException(User.class, "name", loginName);
        } else {
            return create(user);
        }
    }

    public UserDetails create(User user) {
        return new JwtUser(
                user.getUserId(),
                user.getLoginName(),
                user.getPassword(),
                user.getAvatar(),
                user.getEmail(),
                user.getStatus(),
                user.getCrtTime(),
                user.getUsername(),
                user.getDeptId(),
                user.getMobilePhone(),
                user.getTelephone(),
                user.getUserType(),
                user.getDeptName(),
                user.getRoles()
        );
    }
}
